#include <sqlite3.h>
#include <iostream>
#include <string>

// 检查字段是否已存在
bool isFieldExists(sqlite3* db, const std::string& tableName, const std::string& fieldName) {
    std::string sql = "PRAGMA table_info(" + tableName + ");";
    sqlite3_stmt* stmt;
    int rc = sqlite3_prepare_v2(db, sql.c_str(), -1, &stmt, NULL);
    
    if (rc != SQLITE_OK) {
        std::cerr << "准备SQL语句失败: " << sqlite3_errmsg(db) << std::endl;
        return false;
    }
    
    bool fieldFound = false;
    while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
        std::string columnName = (char*)sqlite3_column_text(stmt, 1);
        if (columnName == fieldName) {
            fieldFound = true;
            break;
        }
    }
    
    sqlite3_finalize(stmt);
    return fieldFound;
}

int main() {
    sqlite3* db;
    char* errMsg = 0;
    int rc;
    
    // 数据库文件路径
    std::string dbPath = "/home/atuchina/桌面/shamlog/hamlog.db";
    
    // 打开数据库
    rc = sqlite3_open(dbPath.c_str(), &db);
    
    if (rc) {
        std::cerr << "无法打开数据库: " << sqlite3_errmsg(db) << std::endl;
        sqlite3_close(db);
        return 1;
    }
    
    std::cout << "成功打开数据库: " << dbPath << std::endl;
    
    // 检查frequency字段是否已存在
    if (isFieldExists(db, "qso_records", "frequency")) {
        std::cout << "frequency字段已存在于qso_records表中" << std::endl;
        sqlite3_close(db);
        return 0;
    }
    
    // 执行SQL语句添加frequency字段
    const char* sql = R"(
        ALTER TABLE qso_records
        ADD COLUMN frequency TEXT NOT NULL DEFAULT '0.0';
    )";
    
    rc = sqlite3_exec(db, sql, 0, 0, &errMsg);
    
    if (rc != SQLITE_OK) {
        std::cerr << "执行SQL语句失败: " << errMsg << std::endl;
        sqlite3_free(errMsg);
        sqlite3_close(db);
        return 1;
    }
    
    std::cout << "成功添加frequency字段到qso_records表中" << std::endl;
    
    // 验证字段是否添加成功
    const char* verifySql = "PRAGMA table_info(qso_records);";
    sqlite3_stmt* stmt;
    rc = sqlite3_prepare_v2(db, verifySql, -1, &stmt, NULL);
    
    if (rc != SQLITE_OK) {
        std::cerr << "准备验证SQL语句失败: " << sqlite3_errmsg(db) << std::endl;
        sqlite3_close(db);
        return 1;
    }
    
    std::cout << "qso_records表结构:" << std::endl;
    bool frequencyFieldFound = false;
    while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
        std::string fieldName = (char*)sqlite3_column_text(stmt, 1);
        std::string fieldType = (char*)sqlite3_column_text(stmt, 2);
        std::cout << "字段: " << fieldName << " 类型: " << fieldType << std::endl;
        
        if (fieldName == "frequency") {
            frequencyFieldFound = true;
        }
    }
    
    sqlite3_finalize(stmt);
    
    if (frequencyFieldFound) {
        std::cout << "验证成功: frequency字段已添加到qso_records表中" << std::endl;
    } else {
        std::cout << "验证失败: frequency字段未找到" << std::endl;
    }
    
    sqlite3_close(db);
    return 0;
}